package com.library;

import java.io.IOException;
import java.util.Date;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;

import com.library.model.Book;
import com.library.model.impl.BookImpl;
import com.library.service.BookLocalServiceUtil;
import com.liferay.portal.SystemException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

// Portlet implementation Class Addbook

public class Addbook extends MVCPortlet{

	// Methode assure la mise a jour des informations d'un ou plsr livres
	public void updateBook(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {
		
		String bookTitle = ParamUtil.getString(actionRequest, "bookTitle");
		String author = ParamUtil.getString(actionRequest, "author");
		
		int bookId = ParamUtil.getInteger(actionRequest, "bookId");
		
		Book book = null;
		if (bookId > 0) {
			try {
				book = BookLocalServiceUtil.getBook(bookId);
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			book = new BookImpl();
		}
			
				
		// set UI fields
		book.setBookTitle(bookTitle);
		book.setAuthor(author);
		
		if (bookId > 0) {
			modifyBook(book);
		} else {
			addBook(book);
		}
		
		// redirection vers la page par default "view"
		String redirectURL = ParamUtil.getString(actionRequest, "redirectURL");
		actionResponse.sendRedirect(redirectURL);
		
	}
	private void addBook(Book book) {
			
		// inserer Book en utilisant persistence api
		try {
			BookLocalServiceUtil.addBook(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// cette methode se base sur updateBook
private void modifyBook(Book book) {
		
		try {
			BookLocalServiceUtil.updateBook(book);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	// assure la suppression de Book par leur "bookId"
	public void deleteBook(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {
	
		int bookId = ParamUtil.getInteger(actionRequest, "bookId");
		
		if (bookId > 0) {
			try {
				BookLocalServiceUtil.deleteBook(bookId);
			} catch (PortalException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		// redirection vers la page par default "view"
		String redirectURL = ParamUtil.getString(actionRequest, "redirectURL");
		actionResponse.sendRedirect(redirectURL);
	}
}
